<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">录入数据</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="fungusHarvestList"
      border
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column type="expand">
        <template slot-scope="{row}">
          <el-form label-position="left" class="table-expand">
            <el-form-item label="种植编号">
              <span>{{ row.plantId }}</span>
            </el-form-item>
            <el-form-item label="采收日期">
              <span>{{ row.createDate | dateFilter }}</span>
            </el-form-item>
            <el-form-item label="采收标题">
              <span>{{ row.harvestName }}</span>
            </el-form-item>
            <el-form-item label="采收批次">
              <span>{{ row.batch }}</span>
            </el-form-item>
            <el-form-item label="采收方式">
              <span>{{ row.harvestWay }}</span>
            </el-form-item>
            <el-form-item label="采收图片">
              <el-image
                class="image"
                :src="imgUrl + '/' + row.image"
                :preview-src-list="[imgUrl + '/' + row.image]"
                fit="cover"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="编号" align="center" width="90px" type="index" :index="indexMethod" />
      <el-table-column label="采收日期" align="center" width="120px">
        <template slot-scope="{row}">
          <span>{{ row.createDate | dateFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采收标题" align="center" :show-overflow-tooltip="true">
        <template slot-scope="{row}">
          <span>{{ row.harvestName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采收批次" align="center">
        <template slot-scope="{row}">
          <span>{{ row.batch }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采收方式" align="center">
        <template slot-scope="{row}">
          <span>{{ row.harvestWay }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="100px"
        class-name="small-padding fixed-width"
        width="100px"
      >
        <template slot-scope="{row}">
          <el-button type="danger" size="mini" @click="handleDelete(row.harvestId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="采收方式" prop="harvestWay">
          <el-input v-model="temp.harvestWay" />
        </el-form-item>
        <el-form-item label="采收对象" prop="plantId">
          <el-select
            v-model="temp.plantId"
            class="select"
            placeholder="请选择"
            :disabled="plantFlag"
          >
            <el-option
              v-for="item in fungusPlantOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采收日期" prop="createDate">
          <el-date-picker
            v-model="temp.createDate"
            format="yyyy年MM月dd日"
            value-format="yyyy-MM-dd"
            class="select"
            align="right"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="采收图片" prop="image">
          <el-upload
            ref="uploadImage"
            :action="uploadFileUrl"
            name="file"
            :data="data"
            :auto-upload="false"
            list-type="picture-card"
            :limit="1"
            :on-success="handleSuccess"
            :on-preview="handlePictureCardPreview"
            :on-exceed="handleExceed"
            :on-change="handleChange"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :disabled="plantFlag" @click="dialogStatus==='add'?addData():modifiedData()">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { queryFungusHarvest, deleteFungusHarvest, addFungusHarvest } from '@/api/fungusHarvest'
import { queryFungusPlant } from '@/api/fungusPlant'
import { queryFungusType } from '@/api/fungusType'
import { getSingleBase } from '@/api/base'
import { queryPlace } from '@/api/place'
import { parseTime, formatNumber, codeDate, dateToString } from '@/utils'
import elDragDialog from '@/directive/el-drag-dialog'
import store from '@/store'
import { fungusMixin } from '@/mixins/fungusMixin'

export default {
  name: 'FungusHarvest',
  directives: { elDragDialog },
  filters: {
    dateFilter(date) {
      return date.substring(0, 11)
    }
  },
  mixins: [fungusMixin],
  data() {
    const IMAGE_FILE_NAME = 'harvestImage'

    return {
      category: 'fungus_harvest',
      tableKey: 0,
      disabled: false,
      fungusHarvestList: [],
      listLoading: true,
      listQuery: {
        harvestId: '',
        type: 'fungus',
        plantId: '',
        account: store.getters.token
      },
      fungusPlantQueryList: {
        plantFungusId: '',
        fungusTypeId: -1,
        siteId: -1,
        placeId: -1,
        account: store.getters.token
      },
      fungusPlantOptions: [],
      data: { // 上传图片的参数
        account: store.getters.token,
        path: IMAGE_FILE_NAME
      },
      temp: {
        harvestId: '',
        harvestName: '',
        harvestWay: '',
        type: 'fungus',
        dateCode: '',
        plantId: '',
        batch: '',
        createDate: parseTime(new Date(), '{y}-{m}-{d}'),
        image: '',
        account: store.getters.token
      },
      rules: {
        harvestWay: [
          {
            type: 'string',
            required: true,
            message: '请填写采收方式',
            trigger: 'change'
          }
        ],
        plantId: [
          {
            required: true,
            message: '请选择采收对象',
            trigger: 'change'
          }
        ],
        createDate: [
          {
            type: 'string',
            required: true,
            message: '请选择采收日期',
            trigger: 'change'
          }
        ],
        image: [
          {
            type: 'string',
            required: true,
            message: '请选择采收图片',
            trigger: 'change'
          }
        ]
      },
      dialogStatus: '',
      dialogFormVisible: false,
      dialogVisible: false,
      dialogImageUrl: '',
      textMap: {
        add: '录入数据'
      },
      imgUrl: process.env.VUE_APP_BASE_IMAGE_API + IMAGE_FILE_NAME,
      uploadFileUrl: store.getters.uploadFileUrl,
      siteName: '',
      placeName: '',
      fungusTypeName: ''
    }
  },
  computed: {
    plantFlag() {
      return this.fungusPlantOptions[0].value === -1
    }
  },
  watch: {
    'temp.plantId': {
      handler(newName, oldName) {
        if (newName !== '') {
          this.getBatch()
          const siteId = Number.parseInt(newName.substring(0, 3))
          const placeId = Number.parseInt(newName.substring(3, 6))
          const fungusTypeId = Number.parseInt(newName.substring(13, 16))
          this.getBase(siteId)
          this.getPlace(placeId)
          this.getFungusType(fungusTypeId)
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // fetchData() {
    //   this.listLoading = true
    //   queryFungusHarvest(this.listQuery)
    //     .then(response => {
    //       this.fungusHarvestList = response.Harvest.reverse()
    //       setTimeout(() => {
    //         this.listLoading = false
    //       }, 0.5 * 1000)
    //     })
    //     .catch(error => {
    //       console.log(error)
    //     })
    // },
    getFungusPlant() {
      queryFungusPlant(this.fungusPlantQueryList)
        .then(response => {
          const fungusPlant = response.PlantFungus
          this.fungusPlantOptions = fungusPlant.map(item => {
            return {
              label: item.plantFungusName,
              value: item.plantFungusId
            }
          })
          if (this.fungusPlantOptions.length === 0) {
            this.fungusPlantOptions.push({
              label: '请先添加种植信息',
              value: -1
            })
            this.disabled = true
          }
          this.temp.plantId = this.fungusPlantOptions[0].value
        })
        .catch(error => {
          console.log(error)
        })
    },
    getBatch() {
      const queryList = {
        harvestId: '',
        plantId: this.temp.plantId,
        type: 'fungus',
        account: ''
      }
      queryFungusHarvest(queryList)
        .then(response => {
          const fungusHarvest = response.Harvest
          if (fungusHarvest.length === 0) {
            this.temp.batch = 1
          } else {
            this.temp.batch = Number.parseInt(fungusHarvest[0].batch) + 1
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getBase(siteId) {
      getSingleBase({ siteId })
        .then(response => {
          this.siteName = response.site.siteName
        })
        .catch(error => {
          console.log(error)
        })
    },
    getPlace(placeId) {
      queryPlace({
        placeId,
        siteId: -1,
        limit: -1,
        pageNumber: 0,
        type: ''
      })
        .then(response => {
          this.placeName = response.places[0].placeName
        })
        .catch(error => {
          console.log(error)
        })
    },
    getFungusType(fungusTypeId) {
      queryFungusType({
        fungusTypeId,
        account: ''
      })
        .then(response => {
          this.fungusTypeName = response.FungusType[0].name
        })
        .catch(error => {
          console.log(error)
        })
    },
    resetTemp() {
      this.temp = {
        harvestId: '',
        harvestName: '',
        harvestWay: '',
        type: 'fungus',
        dateCode: '',
        plantId: this.temp.plantId,
        batch: '',
        createDate: parseTime(new Date(), '{y}-{m}-{d}'),
        image: '',
        account: store.getters.token
      }
    },
    handleAdd() {
      this.resetTemp()
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      // this.getFungusPlant()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    addData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$refs['uploadImage'].submit()
        }
      })
    },
    handleSuccess(response, file, fileList) {
      fileList.pop()
      this.temp.image = response.fileName
      this.temp.dateCode = codeDate(this.temp.createDate)
      this.temp.harvestId = this.temp.plantId + this.temp.dateCode + formatNumber(this.temp.batch)
      this.temp.harvestName = dateToString(this.temp.createDate) + this.siteName + this.placeName + this.fungusTypeName + formatNumber(this.temp.batch) + '批次采收'
      addFungusHarvest(this.temp).then(response => {
        this.fungusHarvestList.unshift(this.temp)
        this.dialogFormVisible = false
        this.$notify({
          title: '提示',
          message: '添加成功！',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleDelete(id) {
      this.$msgbox
        .confirm('您确定要删除这条数据吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          deleteFungusHarvest({ harvestId: id })
            .then(response => {
              const index = this.fungusHarvestList.findIndex(
                v => v.harvestId === id
              )
              this.fungusHarvestList.splice(index, 1)
              this.$notify({
                title: '提示',
                message: '删除成功！',
                type: 'success',
                duration: 2000
              })
            })
            .catch(error => {
              console.log(error)
              this.$notify({
                title: '提示',
                message: '删除失败！',
                type: 'error',
                duration: 2000
              })
            })
        })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleChange(file, fileList) {
      if (this.temp.image === '') {
        this.temp.image = 'hasImage'
      }
    },
    handleRemove(file, fileList) {
      if (fileList.length === 0) {
        this.temp.image = ''
      }
    },
    handleExceed(file) {
      this.$message({
        message: '当前版本只支持上传一张图片！',
        type: 'warning'
      })
    },
    indexMethod(index) {
      return index + 1
    }
  }
}
</script>

<style scoped>
.select {
  width:100%;
}

.image {
  width: 250px;
  height: 200px;
  border-radius: 5px;
  background-color: rgb(235,235,235);
  display:flex;
  justify-content: center;
  align-items: center;
}
</style>
